<?php
class Shopfiy extends CI_Controller{

	
	function push_product($limit = 0){
        ignore_user_abort(TRUE);
        set_time_limit(0);
        $mlimit = $limit + 1;
        $offset = 10;
        $limit = $limit * $offset;
        $sql = "SELECT * FROM mall_products WHERE status = 0 ORDER BY id ASC LIMIT $limit, $offset";
        // $sql = "SELECT * FROM mall_products WHERE id=4";
        $product_list = $this->db->query($sql)->result_array();
        // print_r($product_list);exit;
        if(count($product_list) <= 0){
            echo '跑完了';exit;
        }
        $opts = array( 
            'http'=>array( 
            'method'=>'GET',
            'timeout'=>60
            ) 
        ); 
        $context = stream_context_create($opts); 
        foreach ($product_list as $key => $value) {
            $local = false;
            if($value['local_imgs']){
                $local = true;
                $images = explode(",", $value['local_imgs']);
            }else{
                $images = explode(",", $value['imgs']);
            }
            $attachment = $new_local_img = array();
            if(count($images) > 0){
                foreach ($images as $i => $v) {
                    if($local == false){
                        $info = getimagesize($v);
                        if($info['mime'] == 'image/jpeg'){
                            $suffix = '.jpg';
                        }elseif($info['mime'] == 'image/png'){
                            $suffix = '.png';
                        }elseif($info['mime'] == 'image/gif'){
                            $suffix = '.gif';
                        }
                        $img_info = explode("/", $v);
                        $img_path = 'static/shopfiy/'.$value['id'].'_'.end($img_info).$suffix;
                        $image = file_get_contents($v, false, $context);
                        file_put_contents($img_path, $image);
                        $new_local_img[] = $img_path;
                    }else{
                        $img_path = $v;
                    }
                    $base64_img = base64EncodeImage($img_path);
                    $attachment[] = array("attachment" => $base64_img);
                }
                if(count($new_local_img) > 0){
                    $images = implode(",", $new_local_img);
                    $sql = "UPDATE mall_products SET local_imgs='{$images}' WHERE id = '{$value['id']}'";
                    $this->db->query($sql);
                }
            }
            $size = explode(",", $value['size']);
            $color = explode(",", $value['color']);
            $size = array_unique($size);
            $color = array_unique($color);
            $options = $variants = array();
            foreach ($size as $k1 => $v1) {
                if(empty($v1)){
                    unset($size[$k1]);
                }
            }
            if(count($size) > 0){
                $options[] = array("name" => "SIZE", "VALUE" => array_values($size));
            }
            foreach ($color as $k2 => $v2) {
                if(empty($v2)){
                    unset($color[$k2]);
                }
            }
            if(count($color) > 0){
                $options[] = array("name" => "COLOR", "VALUE" => array_values($color));
            }

            if(count($color) > 0 && count($size) > 0){
                foreach ($color as $ck => $c) {
                    foreach ($size as $sk => $s) {
                        $insert_array = array("price" => $value['price']);
                        if(!empty($s)){
                            $insert_array['option1'] = $s;
                        }
                        if( !empty($c)){
                            $insert_array['option2'] = $c;
                        }
                        $variants[] = $insert_array;
                    }
                }
            }elseif (count($color) > 0 && count($size) <= 0) {
                foreach ($color as $ck => $c) {
                    $insert_array = array("price" => $value['price']);
                    if(!empty($c)){
                        $insert_array['option1'] = $c;
                    }
                    $variants[] = $insert_array;
                }
            }elseif (count($color) <= 0 && count($size) > 0) {
                foreach ($size as $sk => $s) {
                    $insert_array = array("price" => $value['price']);
                    if(!empty($s)){
                        $insert_array['option1'] = $s;
                    }
                    $variants[] = $insert_array;
                }
            }

            $pattern = '/<li.*?>.*?Item Code:(.+?)<\/li>/is';
            preg_match_all($pattern, $value['detail'], $results);
            if(!empty($results[0])){
                $value['detail'] = str_replace($results[0], '', $value['detail']);
            }
            // echo $value['detail'];exit;
            $push_data['product']['title'] = $value['product_name'];
            $push_data['product']['vendor'] = '';
            $push_data['product']['product_type'] = $value['category'];
            $push_data['product']['options'] = $options;
            $push_data['product']['variants'] = $variants;
            $push_data['product']['images'] = $attachment;
            $push_data['product']['published'] = true;
            $push_data['product']['metafields_global_description_tag'] = '&nbsp;';
            $push_data['product']['tags'] = $value['keywords'];
            $push_data['product']['body_html'] = $value['detail'];
            // echo json_encode($push_data);exit;
            // print_r($push_data);exit;
            $url = "https://9b68f32994046bdb10a6a6562351ed93:5b9e7db6e70a8c1dd02ce93bc662e17e@prechic2018.myshopify.com/admin/products.json";
            $result = curlRequest($url, $push_data, "POST", true);
            $result = json_decode($result, true);
            // print_r($result);exit;
            if(!empty($result['product'])){
                $sql = "UPDATE mall_products SET status=1, shopify_pid='{$result['product']['id']}' WHERE id = '{$value['id']}'";
                $this->db->query($sql);
            }
            echo $value['id'] . '<br>';
        }
        header("location:/shopfiy/push_product/".$mlimit);
    }


    function push_product_desc($limit = 0){
        set_time_limit(0);
        $mlimit = $limit + 1;
        $offset = 10;
        $limit = $limit * $offset;
        $sql = "SELECT * FROM mall_products WHERE status = 0 ORDER BY id ASC LIMIT 0, 1";
        $product_list = $this->db->query($sql)->result_array();
        foreach ($product_list as $key => $value) {
            $local = false;
            if($value['local_imgs']){
                $local = true;
                $images = explode(",", $value['local_imgs']);
            }else{
                $images = explode(",", $value['imgs']);
            }
            $attachment = $new_local_img = array();
            if(count($images) > 0){
                foreach ($images as $i => $v) {
                    if($local == false){
                        $info = getimagesize($v);
                        if($info['mime'] == 'image/jpeg'){
                            $suffix = '.jpg';
                        }elseif($info['mime'] == 'image/png'){
                            $suffix = '.png';
                        }elseif($info['mime'] == 'image/gif'){
                            $suffix = '.gif';
                        }
                        $img_info = explode("/", $v);
                        $img_path = 'static/shopfiy/'.$value['id'].'_'.end($img_info).$suffix;
                        $image = file_get_contents($v);
                        file_put_contents($img_path, $image);
                        $new_local_img[] = $img_path;
                    }else{
                        $img_path = $v;
                    }
                    $base64_img = base64EncodeImage($img_path);
                    $attachment[] = array("attachment" => $base64_img);
                }
                if(count($new_local_img) > 0){
                    $images = implode(",", $new_local_img);
                    $sql = "UPDATE mall_products SET local_imgs='{$images}' WHERE id = '{$value['id']}'";
                    $this->db->query($sql);
                }
            }
            $size = explode(",", $value['size']);
            $color = explode(",", $value['color']);
            $size = array_unique($size);
            $color = array_unique($color);
            $options = $variants = array();
            foreach ($size as $k1 => $v1) {
                if(empty($v1)){
                    unset($size[$k1]);
                }
            }
            if(count($size) > 0){
                $options[] = array("name" => "SIZE", "VALUE" => $size);
            }

            foreach ($color as $k2 => $v2) {
                if(empty($v2)){
                    unset($color[$k2]);
                }
            }
            if(count($color) > 0){
                $options[] = array("name" => "COLOR", "VALUE" => $color);
            }
            foreach ($color as $ck => $c) {
                foreach ($size as $sk => $s) {
                    $insert_array = array("price" => $value['price']);
                    if(!empty($s)){
                        $insert_array['option1'] = $s;
                    }
                    if( !empty($c)){
                        $insert_array['option2'] = $c;
                    }
                    $variants[] = $insert_array;
                }
            }

            $push_data['product']['title'] = $value['product_name'];
            $push_data['product']['body_html'] = $value['detail'];
            $push_data['product']['vendor'] = '';
            $push_data['product']['product_type'] = $value['category'];
            $push_data['product']['options'] = $options;
            $push_data['product']['variants'] = $variants;
            $push_data['product']['images'] = $attachment;
            $push_data['product']['published'] = false;
            $push_data['product']['metafields_global_description_tag'] = '&nbsp;';
            $push_data['product']['tags'] = $value['keywords'];
            // echo json_encode($push_data);exit;
            $url = "https://9b68f32994046bdb10a6a6562351ed93:5b9e7db6e70a8c1dd02ce93bc662e17e@prechic2018.myshopify.com/admin/products.json";
            $result = curlRequest($url, $push_data, "POST", true);
            $result = json_decode($result, true);
            // print_r($result);
            if(!empty($result['product'])){
                $sql = "UPDATE mall_products SET status=1 WHERE id = '{$value['id']}'";
                $this->db->query($sql);
            }
        }
        header("location:/shopfiy/push_product_desc/".$limit);
    }
}